#### Project: The Racialization of the United States Supreme Court? Examining Changes in Public Opinion Toward SCOTUS Over Time
#### Purpose: YouGov, CCES, and ANES Analysis
#### Date: August 17, 2023
#### Checked: 4.2.2025

# R Studio Version: Version 2024.12.0+467 (2024.12.0+467)

############# 1. General Set-Up #############
# Packages
library(haven)
library(dplyr)
library(ggplot2)
library(texreg)
library(readr)
library(rio)
library(survey)
library(xtable)
library(readxl)
library(zoo)

# Functions
odds.ratio = function(model,variable){
  exp(summary(model)$coefficients[variable,1] + 
        qnorm(c(0.025,0.5,0.975)) * summary(model)$coefficients[variable,2])
}
logit.pred = function(model,new.data,se = T, out = "response"){
  temp = predict(model,newdata = new.data,se.fit=se,type=out)
  temp2 = data.frame("est" = temp$fit,
                     "se" = temp$se.fit,
                     "lower" = temp$fit - 1.96 * temp$se.fit,
                     "upper" = temp$fit + 1.96 * temp$se.fit)
  return(temp2)
}
prop.test.values = function(generated.table,rounding.number=3){
  n = sum(generated.table)
  temp = prop.test(generated.table)
  prop.1 = temp$estimate[1]
  prop.2 = temp$estimate[2]
  dif = prop.1-prop.2
  lower = temp$conf.int[1]
  upper = temp$conf.int[2]
  p = temp$p.value
  temp2 = prop.test(generated.table,conf.level = 0.9)
  lower90 = temp2$conf.int[1]
  upper90 = temp2$conf.int[2]
  out = data.frame("n" = n,
                   "prop.1" = prop.1,
                   "prop.2"=prop.2,
                   "difference"=dif,
                   "lower.ci"=lower,
                   "upper.ci"=upper,
                   "lower90.ci"=lower90,
                   "upper90.ci"=upper90,
                   "p.value"=p)
  return(out)
}
dif.of.means.fun = function(var1,var2){
  temp = t.test(var1,var2)
  p = temp$p.value
  mean.1 = temp$estimate[1]
  mean.2 = temp$estimate[2]
  lower = temp$conf.int[1]
  upper = temp$conf.int[2]
  temp2 = t.test(var1,var2,conf.level = 0.9)
  lower90 = temp2$conf.int[1]
  upper90 = temp2$conf.int[2]
  difference = mean.1 - mean.2 
  out = data.frame("mean.1" = mean.1,
                   "mean.2"=mean.2,
                   "difference"=difference,
                   "lower.ci"=lower,
                   "upper.ci"=upper,
                   "lower90.ci"=lower90,
                   "upper90.ci"=upper90,
                   "p.value"=p)
  return(out)
}
std.error <- function(x){sd(x,na.rm=T)/sqrt(sum(!is.na(x)))}
summary.function = function(variables = NULL, names = NULL){
  
  output = data.frame("Minimum"=rep(NA,dim(variables)[2]),
                      "Median"=rep(NA,dim(variables)[2]),
                      "Mean"=rep(NA,dim(variables)[2]),
                      "Maximum"=rep(NA,dim(variables)[2]),
                      "Standard.Deviation"=rep(NA,dim(variables)[2]),
                      "Missing"=rep(NA,dim(variables)[2]))
  
  output$Minimum = apply(variables,2,function(x){min(x,na.rm=T)})
  output$Median = apply(variables,2,function(x){median(x,na.rm=T)})
  output$Mean = apply(variables,2,function(x){mean(x,na.rm=T)})
  output$Maximum = apply(variables,2,function(x){max(x,na.rm=T)})
  output$Standard.Deviation = apply(variables,2,function(x){sd(x,na.rm=T)})
  output$Missing = apply(variables,2,function(x){sum(is.na(x))})
  
  if(!is.null(names)){rownames(output) = names}
  
  return(output)
}

# Color Pallatte for Figures
cbp2 <- c("#000000", "#E69F00", "#56B4E9", "#009E73",
          "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

# Setting the Working Directory.
setwd("~/Replication Files - POBE/")


############# 2a. ANES - Cleaning #############
# The Data
anes <- read_dta("Data/anes_timeseries_cdf_stata_20211118.dta")

# Cleaning the data.
anes.sm = anes %>% 
  mutate(thermom_sc = ifelse(VCF9005 > 97, NA, VCF9005),
         thermom_blk = ifelse(VCF0206 > 97, NA, VCF0206),
         thermom_wht = ifelse(VCF0207 > 97, NA, VCF0207),
         thermom_own = ifelse(VCF0105b == 1, thermom_wht, 
                              ifelse(VCF0105b == 2,
                                     thermom_blk,NA)),
         thermom_other = ifelse(VCF0105b == 2, thermom_wht, 
                                ifelse(VCF0105b == 1,
                                       thermom_blk,NA)),
         thermom_dif1 = thermom_own - thermom_other,
         thermom_dif2 = thermom_wht - thermom_blk,
         thermom_lgbt = VCF0232/100,
         race_wht = ifelse(VCF0105b == 1, 1, 0),
         race_blk = ifelse(VCF0105b == 2, 1, 0),
         rr1 = (ifelse(VCF9040>5, NA, VCF9040)-5)*-1,
         rr2 = ifelse(VCF9039>5, NA, VCF9039) - 1,
         rr = (rr1+rr2)/2,
         year = VCF0004,
         year2 = factor(VCF0004),
         age = ifelse(VCF0101==0,NA,VCF0101),
         woman = ifelse(VCF0104==2,1,
                        ifelse(VCF0104==1,0,NA)),
         income = ifelse(VCF0114==0,NA,VCF0114),
         education = ifelse(VCF0140>6,NA,VCF0140),
         pid3 = ifelse(VCF0303<1,NA,
                       ifelse(VCF0303==2, "0 Independents",
                              ifelse(VCF0303==1,"1 Democrat","2 Republican"))),
         election_int = ifelse(VCF0310 %in% c(0,9),NA,VCF0310),
         govt_trust = ifelse(VCF0656>100,NA,VCF0656),
         black = ifelse(race_blk == 1, "Yes","No"), 
         ideo = ifelse(VCF0803>7,NA,VCF0803)) %>%
  filter(year >1979)

############# 2b. ANES - Analysis #############

# Updating the key variables. 
anes.sm$rr = anes.sm$rr/4
anes.sm$thermom_dif2 = anes.sm$thermom_dif2/100
anes.sm$birth.yr = anes.sm$year - anes.sm$age

# Regressions
reg.anes.wht1 = lm(thermom_sc ~ thermom_dif2*year2+
                     govt_trust + age + woman + 
                     income + education +
                     pid3 + ideo + election_int,
                   data = anes.sm %>% 
                     filter(race_wht == 1))#,weights = anes.sm$VCF0009z[anes.sm$race_wht==1])
reg.anes.wht2 = lm(thermom_sc ~ thermom_dif2*year2+
                     govt_trust + age + woman + 
                     income + education +
                     pid3 + ideo +  election_int,
                   data = anes.sm %>% 
                     filter(race_wht == 1),
                   weights = anes.sm$VCF0009z[anes.sm$race_wht==1])
reg.anes.wht2rr = lm(thermom_sc ~ rr*year2+
                       govt_trust + age + woman + 
                       income + education +
                       pid3 + ideo +  election_int,
                     data = anes.sm %>% 
                       filter(race_wht == 1),
                     weights = anes.sm$VCF0009z[anes.sm$race_wht==1])

# Reg Table: Table 1: OLS Regressions Explaining Feelings Toward the Supreme Court [In body of paper]
texreg(list(reg.anes.wht2,reg.anes.wht2rr),stars=0.05,
       custom.coef.map = list("(Intercept)"="(Intercept)",
                              "thermom_dif2"="Feelings Toward White-Black People",
                              "rr"="Racial Resentment",
                              "year21984"="1984",
                              "year21988"="1988",
                              "year21996"="1996",
                              "year22000"="2000",
                              "year22004"="2004",
                              "year22008"="2008",
                              "year22012"="2012",
                              "year22016"="2016",
                              "year22020"="2020",
                              "thermom_dif2:year21984"="1984*Racial Attitude",
                              "thermom_dif2:year21988"="1988*Racial Attitude",
                              "thermom_dif2:year21996"="1996*Racial Attitude",
                              "thermom_dif2:year22000"="2000*Racial Attitude",
                              "thermom_dif2:year22004"="2004*Racial Attitude",
                              "thermom_dif2:year22008"="2008*Racial Attitude",
                              "thermom_dif2:year22012"="2012*Racial Attitude",
                              "thermom_dif2:year22016"="2016*Racial Attitude",
                              "thermom_dif2:year22020"="2020*Racial Attitude",
                              "rr:year21984"="1984*Racial Attitude",
                              "rr:year21988"="1988*Racial Attitude",
                              "rr:year21996"="1996*Racial Attitude",
                              "rr:year22000"="2000*Racial Attitude",
                              "rr:year22004"="2004*Racial Attitude",
                              "rr:year22008"="2008*Racial Attitude",
                              "rr:year22012"="2012*Racial Attitude",
                              "rr:year22016"="2016*Racial Attitude",
                              "rr:year22020"="2020*Racial Attitude"))

# Predictions. 
n.wht = length(-97:97)
newdata.wht = data.frame("thermom_dif2"=c(-97:97,-97:97,-97:97)/100,
                         "year2"=factor(c(rep(1980,n.wht),
                                          rep(2000,n.wht),
                                          rep(2020,n.wht))),
                         "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                         "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                         "woman"=1,
                         "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                         "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                         "pid3"="2 Republican",
                         "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                         "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T))
newdata.wht.rr = data.frame("rr"=c(seq(0,1,by=0.1),seq(0,1,by=0.1),seq(0,1,by=0.1)),
                            "year2"=factor(c(rep(1988,length(seq(0,1,by=0.1))),
                                             rep(2000,length(seq(0,1,by=0.1))),
                                             rep(2020,length(seq(0,1,by=0.1))))),
                            "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                            "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                            "woman"=1,
                            "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                            "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                            "pid3"="2 Republican",
                            "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                            "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T))
pred.wht = predict(reg.anes.wht2,
                   newdata = newdata.wht,
                   interval="prediction",
                   se.fit=T)
newdata.wht$mean = pred.wht$fit[,1]
newdata.wht$lower = pred.wht$fit[,1] - 1.96*pred.wht$se.fit
newdata.wht$upper = pred.wht$fit[,1] + 1.96*pred.wht$se.fit

pred.wht.rr = predict(reg.anes.wht2rr,
                      newdata = newdata.wht.rr,
                      interval="prediction",
                      se.fit=T)
newdata.wht.rr$mean = pred.wht.rr$fit[,1]
newdata.wht.rr$lower = pred.wht.rr$fit[,1] - 1.96*pred.wht.rr$se.fit
newdata.wht.rr$upper = pred.wht.rr$fit[,1] + 1.96*pred.wht.rr$se.fit

# The figures: Figure 1: Predicted Values of Feelings Toward the Supreme Court by Year and Racial Attitude [In body of paper]
cbp2 <- c("#000000", "#E69F00", "#56B4E9", "#009E73",
          "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

fig.pred.prob.wht = ggplot(newdata.wht, aes(thermom_dif2,mean,linetype=year2)) + 
  geom_line(size=1) + 
  theme_bw(base_size = 12) +
  theme(legend.position = "bottom") +
  guides(color=guide_legend(title="Year"),
         linetype=guide_legend(title="Year")) +
  scale_color_manual(values=cbp2) +
  xlab("White - Black Feelings \nThermometer") +
  ylab("Feelings Toward the \nSupreme Court") + 
  ylim(0,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)



fig.pred.prob.wht.rr = ggplot(newdata.wht.rr, aes(rr,mean,linetype=year2)) + 
  geom_line(size=1) + 
  theme_bw(base_size = 12) +
  theme(legend.position = "bottom") +
  guides(color=guide_legend(title="Year"),
         linetype=guide_legend(title="Year")) +
  scale_color_manual(values=cbp2) +
  xlab("Racial Resentment Scale") +
  ylab("Feelings Toward the \nSupreme Court") + 
  ylim(0,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)

cowplot::plot_grid(fig.pred.prob.wht,
                   fig.pred.prob.wht.rr,
                   labels=c("a.","b."))

# Saving the figure. 
pdf("Figures/Fig_ANES_PredProb_WhiteRespOnly.pdf",7.49,4.03)
cowplot::plot_grid(fig.pred.prob.wht,fig.pred.prob.wht.rr,
                   labels=c("a.","b."))
dev.off()

############# 3a. ANES - Court Salience - Cleaning ############# 

# Loading in the data on individual supreme court cases.
cases <- read_excel("Data/SCDB_2023_01_caseCentered_Citation.xlsx")

# Loading in the topic and case coding data.
topic_list = read_excel("Data/Issue Codes (1).xlsx")
indiv_case_coding = read_excel("Data/RacializedCases - Coding.xlsx")
indiv_case_coding2 = read_excel("Data/RacializedCases2 - Coding.xlsx")
indiv_case_coding = bind_rows(indiv_case_coding, indiv_case_coding2)

# Loadting in data on the salience of each court case. 
salience <- read_excel("Data/CSI_1953_2014.xls")
salience15 <- read_excel("Data/DataCollectionCSI2015.xlsx")
salience15 = salience15 %>% 
  select(csi,caseId,laScore,chScore,washScore,nyScore)
salience16 <- read_excel("Data/DataCollectionCSI2016.xlsx")
salience16 = salience16 %>% 
  select(csi,caseId,laScore,chScore,waScore,nyScore)
colnames(salience16)[5] = "washScore"
salience17 <- read_excel("Data/DataCollectionCSI2017.xlsx")
salience17 = salience17 %>% 
  select(csi,caseId,laScore,chScore,waScore,nyScore)
colnames(salience17)[5] = "washScore"
salience18 <- read_excel("Data/DataCollectionCSI2018.xlsx")
salience18 = salience18 %>% 
  select(csi,caseId,laScore,chScore,waScore,nyScore)
colnames(salience18)[5] = "washScore"
salience19 <- read_excel("Data/DataCollectionCSI2019.xlsx")
salience19 = salience19 %>% 
  select(csi,caseId,laScore,chScore,washScore,nyScore)
salience20 <- read_excel("Data/DataCollectionCSI2020.xlsx")
salience20 = salience20 %>% 
  select(csi,caseId,laScore,chScore,washScore,nyScore)
salience21 <- read_excel("Data/DataCollectionCSI2021.xlsx")
salience21 = salience21 %>% 
  select(csi,caseId,laScore,chScore,washScore,nyScore)

# Binding the salience data together.
salience = bind_rows(salience,salience15,
                     salience16,salience17,salience18,
                     salience19,salience20,salience21)

# Calculating salience.
salience$salience <- rowSums(salience[,3:6],na.rm=T)

# Merging individual case information with salience information. 
cases2 = left_join(cases %>% 
                     filter(term>1952 & term !=2022 &
                              decisionType %in% c(1,5,6,7)),
                   salience,by="caseId") %>%
  mutate(nyAny = ifelse(nyScore>0,1,0),
         washAny = ifelse(washScore>0,1,0),
         chAny = ifelse(chScore>0,1,0),
         laAny = ifelse(laScore>0,1,0),
         year = term + 1)
colnames(topic_list) = c("issue","descrip","racialized","notes")
cases2 = left_join(cases2, topic_list %>% 
                     select(issue,descrip,racialized))

# Merging in case-level coding based on the limited pull from cases3. 
cases2 = left_join(cases2, 
                   indiv_case_coding %>% 
                     select(caseId,case_specific_racialized,
                            case_specific_notes,source), 
                   by = "caseId")

cases3 = cases2 %>%
  filter(salience>4 & term>1954 & issueArea == 2)
cases3 %>% 
  group_by(racialized,case_specific_racialized) %>%
  summarize(count = n())
table(is.na(cases3$case_specific_racialized))

summary.table = cases2 %>%
  filter(salience>4 & term>1954 & issueArea == 2 & 
           case_specific_racialized == "Likely or is racialized.") %>%
  mutate(salience0 = salience,
         salience1 = ifelse(salience>4,1,0),
         salience2 = nyAny + washAny + chAny + laAny,
         frontpage = ifelse(nyScore == 2|washScore == 2 |
                              chScore == 2 | 
                              laScore == 2,1,0),
         all_covered = ifelse(nyAny>0 & washAny>0 & 
                                chAny>0 & laAny>0, 1, 0),
         salience3 = ifelse(all_covered == 1 &
                              frontpage == 1,
                            1,0)) %>%
  group_by(term,decisionDirection) %>%
  summarize(salience = mean(salience,na.rm=T),
            salience1 = sum(salience1,na.rm=T),
            salience2 = sum(salience2,na.rm=T),
            salience3 = sum(salience3,na.rm=T),
            frontpage = sum(frontpage, na.rm=T)) %>%
  ungroup() %>%
  mutate(Direction = ifelse(decisionDirection==2,"Liberal",
                            ifelse(decisionDirection==1,
                                   "Conservative","Neither"))) %>% 
  right_join(data.frame(term=c(1955:2021,1955:2021),
                        Direction = c(rep("Liberal", length(1955:2021)),
                                      rep("Conservative", length(1955:2021))))) %>% 
  mutate(salience = ifelse(is.na(salience),0,salience),
         salience1 = ifelse(is.na(salience1),0,salience1),
         salience2 = ifelse(is.na(salience2),0,salience2),
         salience3 = ifelse(is.na(salience3),0,salience3),
         frontpage = ifelse(is.na(frontpage),0,frontpage))

############# 3b. ANES - Court Salience - Descriptives #############

# Figure: Figure 2: Number of Highly Salient Supreme Court Cases Dealing with Race and Racial Policies by Decision Over Time (1960-2020) [In body of paper]
pdf(file="Figures/Fig_SCDB_Cases_salienceBYdirection.pdf",8.51,4.2)
ggplot(summary.table %>% 
         filter(Direction %in% c("Liberal","Conservative") & term >1959),
       aes(term, jitter(frontpage), shape=Direction, linetype=Direction)) +
  geom_point(size=3,color="darkgrey") +
  geom_smooth(color="black",alpha=0.2) +
  ylab("Number of Highly Salient Cases") +
  xlab("Term") + 
  ylim(-1.25,10)+
  theme_bw(base_size=14) +
  theme(legend.position = "bottom")
dev.off()

# Creating a data set to calculate the difference in the number of cases over time.
summary.liberal = summary.table %>% filter(Direction == "Liberal")
colnames(summary.liberal)[3:8] = c("salience.lib","salience.lib1",
                                   "salience.lib2","salience.lib3",
                                   "frontpage.lib","Liberal")
summary.conservative = summary.table %>% filter(Direction == "Conservative")
colnames(summary.conservative)[3:8] = c("salience.con","salience.con1",
                                        "salience.con2","salience.con3",
                                        "frontpage.con","Conservative")
summary.together = full_join(summary.liberal[,c(1,3:8)],
                             summary.conservative[,c(1,3:8)])
# Calculating the differences in salience.
summary.together = summary.together %>% 
  mutate(salience.dif = salience.lib-salience.con,
         salience.dif1 = salience.lib1-salience.con1,
         salience.dif2 = salience.lib2-salience.con2,
         salience.dif3 = salience.lib3-salience.con3,
         salience.dif4 = frontpage.lib-frontpage.con) %>%
  mutate(cma = zoo::rollmean(salience.dif1, k = 3, fill = NA))

# Figure. Difference in Number of Highly Salient Cases Over Time (Liberal - Conservative)
pdf(file="Figures/Fig_SCDB_Cases_DIFsalience.pdf",8.51,3.85)
ggplot(summary.together %>% filter(term>1955 & term<2021),
       aes(term,cma)) + 
  geom_point() +
  geom_smooth(color="black",alpha=0.2,method="gam") +
  ylab("Difference in Number of Highly Salient Cases\n(Liberal Decisions-Conservative Decisions)") + 
  xlab("Term") +# xlim(1980,2024) +
  ylim(-5,10) +
  theme_bw(base_size=14)
dev.off()

############# 3c. ANES - Court Salience - Measure and Analysis #############

# Due to the choppiness -- and us only looking at select years -- we extract the loess regression estiamtes to use as our measure of salience over time. 
m <- loess(cma~term, data=summary.together)
newvals <- data.frame(term=1955:2020)
cbind(newvals, value=predict(m, newvals))
summary.together$salience.pred = predict(m, summary.together$term)

# Creating the salience data set
summary.together2 = summary.together %>%
  mutate(year = term + 1) %>%
  select(year,salience.pred)
colnames(summary.together2) = c("year","decision_salience")

save(summary.together2,file = "summary.together2.RData")

# The Merge
anes.sm2 = left_join(anes.sm,summary.together2,by="year")

# Regressions
reg.salience.wht1 = lm(thermom_sc ~ thermom_dif2*decision_salience+
                         govt_trust + age + woman + 
                         income + education +
                         pid3 + ideo + election_int,
                       data = anes.sm2 %>% 
                         filter(race_wht == 1))
reg.salience.wht2 = lm(thermom_sc ~ thermom_dif2*decision_salience+
                         govt_trust + age + woman + 
                         income + education +
                         pid3 + ideo +  election_int,
                       data = anes.sm2 %>% 
                         filter(race_wht == 1),
                       weights = anes.sm2$VCF0009z[anes.sm2$race_wht==1])
reg.salience.wht2rr = lm(thermom_sc ~ rr*decision_salience+
                           govt_trust + age + woman + 
                           income + education +
                           pid3 + ideo +  election_int,
                         data = anes.sm2 %>% 
                           filter(race_wht == 1),
                         weights = anes.sm2$VCF0009z[anes.sm2$race_wht==1])

# Regression table: Table 2: OLS Regressions Explaining Feelings Toward the Supreme Court by Difference in Salience of Court Decisions on Racial & Racialized Civil Rights Cases, ANES [In body of paper]
texreg(list(reg.salience.wht2,reg.salience.wht2rr),stars=0.05,
       custom.coef.map = list("(Intercept)"="(Intercept)",
                              "thermom_dif2"="Feelings Toward White-Black People",
                              "rr"="Racial Resentment",
                              "decision_salience"="Salience Difference",
                              "thermom_dif2:decision_salience"="Salience Difference*Racial Attitude",
                              "rr:decision_salience"="Salience Difference*Racial Attitude"))

# Generating Predicted Values: "New Data"
n.wht = length(-97:97)
salience.min = min(anes.sm2$decision_salience,na.rm=T)
salience.med = median(anes.sm2$decision_salience,na.rm=T)
salience.max = max(anes.sm2$decision_salience,na.rm=T)
newdata.wht = data.frame("thermom_dif2"=c(-97:97,-97:97,-97:97)/100,
                         "decision_salience"=(c(rep(salience.min,n.wht),
                                                rep(salience.med,n.wht),
                                                rep(salience.max,n.wht))),
                         "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                         "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                         "woman"=1,
                         "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                         "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                         "pid3"="2 Republican",
                         "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                         "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T))
newdata.wht.rr = data.frame("rr"=c(seq(0,1,by=0.1),seq(0,1,by=0.1),seq(0,1,by=0.1)),
                            "decision_salience"=(c(rep(salience.min,length(seq(0,1,by=0.1))),
                                                   rep(salience.med,length(seq(0,1,by=0.1))),
                                                   rep(salience.max,length(seq(0,1,by=0.1))))),
                            "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                            "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                            "woman"=1,
                            "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                            "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                            "pid3"="2 Republican",
                            "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                            "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T))

# Generating Predicted Values: Predictions + SE
pred.wht = predict(reg.salience.wht2,
                   newdata = newdata.wht,
                   interval="prediction",
                   se.fit=T)
newdata.wht$mean = pred.wht$fit[,1]
newdata.wht$lower = pred.wht$fit[,1] - 1.96*pred.wht$se.fit
newdata.wht$upper = pred.wht$fit[,1] + 1.96*pred.wht$se.fit

pred.wht.rr = predict(reg.salience.wht2rr,
                      newdata = newdata.wht.rr,
                      interval="prediction",
                      se.fit=T)
newdata.wht.rr$mean = pred.wht.rr$fit[,1]
newdata.wht.rr$lower = pred.wht.rr$fit[,1] - 1.96*pred.wht.rr$se.fit
newdata.wht.rr$upper = pred.wht.rr$fit[,1] + 1.96*pred.wht.rr$se.fit

newdata.wht$SalienceDif = ifelse(newdata.wht$decision_salience<salience.med,
                                 "Min.",
                                 ifelse(newdata.wht$decision_salience>salience.med,
                                        "Max.","Median"))
newdata.wht.rr$SalienceDif = ifelse(newdata.wht.rr$decision_salience<salience.med,
                                    "Min.",
                                    ifelse(newdata.wht.rr$decision_salience>salience.med,
                                           "Max.","Median"))

# Figures: Figure 3: Predicted Values of Feelings Toward the Supreme Court by Difference in the Number of Highly Salient Cases and Racial Attitude [In body of paper]
fig.pred.prob.wht = ggplot(newdata.wht, 
                           aes(thermom_dif2,mean,
                               linetype=factor(SalienceDif))) + 
  geom_line(size=1) + 
  theme_bw(base_size = 12) +
  theme(legend.position = "none") +
  #guides(linetype=guide_legend(title="Salience Difference"),nrow=2) +
  xlab("White - Black Feelings\nThermometer") +
  ylab("Feelings Toward the\nSupreme Court") + 
  ylim(45,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)

fig.pred.prob.wht.rr = ggplot(newdata.wht.rr, 
                              aes(rr,mean,linetype=factor(SalienceDif))) + 
  geom_line(size=1) + 
  theme_bw(base_size = 12) +
  theme(legend.position = "right") +
  guides(linetype=guide_legend(title="Salience Dif.\n(Lib.-Con.)")) +
  xlab("Racial Resentment\nScale") +
  ylab("Feelings Toward the\nSupreme Court") + 
  ylim(45,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)

cowplot::plot_grid(fig.pred.prob.wht,
                   fig.pred.prob.wht.rr,
                   labels=c("a.","b."),
                   rel_widths = c(1,1.5))

pdf("Figures/Fig_ANES_PredProb_WhiteRespOnly_Salience.pdf",7.49,3.03)
cowplot::plot_grid(fig.pred.prob.wht,fig.pred.prob.wht.rr,
                   labels=c("a.","b."),
                   rel_widths = c(1,1.5))
dev.off()
######### 4. SCDB -- Civil Rights (mini) Cases Over Time #########

# Change in issue attention over time?
scdb = read_excel("Data/SCDB_2023_01_caseCentered_Citation.xlsx")
topic_list = read_excel("Data/Issue Codes (1).xlsx")

colnames(topic_list)[1:3] = c("issue","descrip","racialized")

# Merging the data together.
scdb = left_join(scdb, topic_list %>% 
                   select(issue,descrip,racialized))

scdb2 = scdb %>%
  filter(term>1954 & racialized != "no" & issue != 20030 & 
           !grepl("immigration",descrip)) %>%
  group_by(term,decisionDirection) %>%
  summarize(Count = length(unique(caseId))) %>%
  ungroup() %>%
  mutate(Direction = ifelse(decisionDirection==2,"Liberal",
                            ifelse(decisionDirection==1,"Conservative","Neither")))

colnames(scdb2)[1] = "Term"

sum(scdb2$Count)
sum(scdb2$Count[scdb2$Term>1979])

# Figure 4: Number of Supreme Court Cases Dealing with Racialized Policies by Decision Over Time (1955-2020) [In body of paper]
pdf(file="Figures/Fig_SCDB_Cases.pdf",8.51,3.85)
ggplot(scdb2 %>% filter(Direction != "Neither" & Term >1954),
       aes(Term, Count, shape=Direction, linetype=Direction)) +
  geom_point(size=3,color="darkgrey") +
  geom_smooth(color="black",alpha=0.2) +
  ylab("Number of Cases") +
  ylim(0,20)+
  theme_bw(base_size=12) +
  theme(legend.position = "bottom")
dev.off()

######### 5a. CES - Cleaning - 2020 #########

# Note: 2017 + 2019 include the racism but not racial resentment questions. 

# Loading in the Data
ces2020 = import("Data/CES/CES20_Common_OUTPUT_vv.dta")

# Selecting the specific variables. 
ces2020 = ces2020 %>% 
  select(caseid,
         CC20_320c,CC20_356,CC20_356a,CC20_350c,
         CC20_340a,
         CC20_441a,CC20_441b,CC20_441e,
         CC20_441f,CC20_441g,
         CC20_440a,CC20_440b,CC20_440c,CC20_440d,
         birthyr,gender,race,hispanic,
         educ,faminc_new,
         pid7,pid3,inputstate_post,region_post,
         newsint,
         commonweight,commonpostweight,
         vvweight,vvweight_post) %>% 
  mutate(year = 2020,
         age = year - birthyr)

colnames(ces2020) = c("caseid","approval_sc", 
                      "approval_acb", "rbg_replace","approval_kavanagh", 
                      "ideo_self","rr1","rr2","rr3","rr4","rr5",
                      "rs1","rs2","rs3","rs4",
                      "birthyr","gender","race","hispanic",
                      "educ","faminc_new",
                      "pid7","pid3","state","region",
                      "newsint",
                      "commonweight","commonpostweight",
                      "vvweight","vvweight_post",
                      "year","age")

# Saving the file.
save(ces2020,file="CES2020.RData")


######### 5b. CES - Cleaning - 2018 #########

# Loading in the Data
ces2018 = import("Data/CES/cces18_common_vv.dta")

# Selecting the specific variables. 
ces2018 = ces2018 %>% 
  select(caseid, 
         CC18_308c,CC18_334F,
         CC18_328b,CC18_328f,
         CC18_334A,
         CC18_422e,CC18_422f,
         CC18_422a,CC18_422b,
         birthyr,gender,race,hispanic,
         educ,faminc_new,
         pid7,pid3,inputstate,region,
         newsint,
         commonweight,commonpostweight,vvweight,vvweight_post) %>% 
  mutate(year = 2018,
         age = year - birthyr)

colnames(ces2018) = c("caseid",
                      "approval_sc","ideo_court",
                      "for_gorsuch","for_kavanagh", 
                      "ideo_self",
                      "rr1","rr2",
                      "rs1","rs2",
                      "birthyr","gender","race","hispanic",
                      "educ","faminc_new",
                      "pid7","pid3","state","region",
                      "newsint","commonweight","commonpostweight",
                      "vvweight","vvweight_post",
                      "year","age")

# Saving the file.
save(ces2018,file="CES2018.RData")


######### 5c. CES - Cleaning - 2016 #########

# Loading in the Data
ces2016 = import("Data/CES/CCES16_Common_OUTPUT_Feb2018_VV.dta")

# Selecting the specific variables. 
ces2016 = ces2016 %>% 
  select(V101, 
         CC16_320c,CC16_340i,CC16_351A,
         CC16_340a,
         CC16_422d,CC16_422f,
         birthyr,gender,race,hispanic,
         educ,faminc,
         pid7,pid3,inputstate,
         newsint,
         commonweight,commonweight_post,commonweight_vv,commonweight_vv_post) %>% 
  mutate(year = 2016,
         age = year - birthyr)

colnames(ces2016) = c("caseid",
                      "approval_sc","ideo_court","for_garland", 
                      "ideo_self",
                      "rs1","rs2",
                      "birthyr","gender","race","hispanic",
                      "educ","faminc_new",
                      "pid7","pid3","state",
                      "newsint","commonweight","commonweight_post",
                      "vvweight","vvweight_post",
                      "year","age")

# Saving the file.
save(ces2016,file="CES2016.RData")

######### 5d. CES - Cleaning - 2014 #########

# Loading in the Data
ces2014 = import("Data/CES/CCES14_Common_Content_Validated.dta")

# Selecting the specific variables. 
ces2014 = ces2014 %>% 
  select(V101, 
         CC14_308c,CC334M,
         CC334A,
         CC422a,CC422b,
         birthyr,gender,race,hispanic,
         educ,faminc,
         pid7,pid3,inputstate,
         newsint,
         weight,CC14_328) %>% 
  mutate(year = 2014,
         age = year - birthyr)

colnames(ces2014) = c("caseid",
                      "approval_sc","ideo_court", 
                      "ideo_self",
                      "rr1","rr2",
                      "birthyr","gender","race","hispanic",
                      "educ","faminc_new",
                      "pid7","pid3","state",
                      "newsint","weight",
                      "affirmative_action",
                      "year","age")

# Saving the file.
save(ces2014,file="CES2014.RData")

######### 5e. CES - Cleaning - 2012 #########

# Loading in the Data
ces2012 = import("Data/CES/CCES12_Common_VV.dta")

# Selecting the specific variables. 
ces2012 = ces2012 %>% 
  select(V101, 
         CC308c,CC334P,CC334A,
         CC422a,CC422b,
         birthyr,gender,race,hispanic,
         educ,faminc,
         pid7,pid3,inputstate,
         newsint,
         V103,weight_vv,weight_vv_post,
         CC327) %>% 
  mutate(year = 2012,
         age = year - birthyr)

colnames(ces2012) = c("caseid",
                      "approval_sc","ideo_court","ideo_self",
                      "rr1","rr2",
                      "birthyr","gender","race","hispanic",
                      "educ","faminc_new",
                      "pid7","pid3","state",
                      "newsint","weight","weight_vv","weight_vv_pos",
                      "affirmative_action",
                      "year","age")

# Saving the file.
save(ces2012,file="CES2012.RData")

#AA
#7448 1 Strongly Support
#13797 2 Somewhat Support
#14183 3 Somewhat Oppose
#18869 4 Strongly Oppose
#238 8 Skipped
#0 9 Not Asked

######### 5f. CES - Cleaning - 2010 #########

# Loading in the Data
ces2010 = import("Data/CES/cces_2010_common_validated.dta")

# Selecting the specific variables. 
ces2010 = ces2010 %>% 
  select(V100, 
         CC308c,CC332E,CC334A,
         CC422a,CC422b,
         V207,V208,V211,V290,
         V213,V246,
         V212d,V212a,V206,
         V244,
         V101,CC327) %>% 
  mutate(year = 2010,
         age = year - V207)

colnames(ces2010) = c("caseid",
                      "approval_sc","for_kagan","ideo_self",
                      "rr1","rr2",
                      "birthyr","gender","race","hispanic",
                      "educ","faminc_new",
                      "pid7","pid3","state",
                      "newsint","weight",
                      "affirmative_action",
                      "year","age")

# Saving the file.
save(ces2010,file="CES2010.RData")

# AA: 
#6638 <1> Strongly support
#12985 <2> Somewhat support
#13326 <3> Somewhat oppose
#22324 <4> Strongly oppose
#127 <8> Skipped
#0 <9> Not Asked

######### 5g. CES - Putting it together. #########

# Putting it together. 
ces = bind_rows(ces2020, ces2018, ces2016,
                ces2014, ces2012, ces2010)

# Saving the file. 
save(ces,file = "Data/CES_Aggregated.RData")

######### 5h. CES - Cleaning #########

# Cleaning. 
ces = ces %>% 
  mutate(approval_sc2 = ifelse(approval_sc==5, NA, approval_sc),
         approval_sc3 = ifelse(approval_sc==5, NA,
                               ifelse(approval_sc>2,0,1)),
         rr1a = (ifelse(rr1>5,NA,rr1)-6)*-1,
         rr2a = ifelse(rr2>5,NA,rr2),
         rr = (rr1a+rr2a)/2,
         race_blk = ifelse(race == 2 & hispanic ==2, 1, 0),
         race_wht = ifelse(race == 1 & hispanic ==2, 1, 0),
         race_wb = ifelse(race == 2, 1, 
                          ifelse(race == 1, 0, NA)),
         gender_male = ifelse(gender == 1, 1, 
                              ifelse(gender == 2, 0, NA)),
         ideo_self = ifelse(ideo_self>7, NA, ideo_self),
         ideo_court = ifelse(ideo_court>7, NA, ideo_court),
         newsint2 = ifelse(newsint>4,NA,newsint),
         ideo_dif = abs(ideo_self - ideo_court),
         pid3a = ifelse(pid7%in%c(1,2,5),1,
                        ifelse(pid7%in%c(3,4,6),2,0)))

######### 5i. CES - Analysis ##########

# Final Clean
ces$rr.raw = ces$rr
ces$rr = (ces$rr.raw-1)/4

seq_rr = seq(0,1,by=0.1)

# Regressions
reg.inter.self = glm(approval_sc3 ~ rr*factor(year) +
                       gender_male + age + 
                       educ + faminc_new + 
                       factor(pid3a) + ideo_self +
                       newsint2 + factor(state), 
                     data = ces %>% filter(race_wht==1),
                     family="binomial")
reg.inter.court = glm(approval_sc3 ~ rr*factor(year) +
                        gender_male + age + 
                        educ + faminc_new + 
                        factor(pid3a) + ideo_self + ideo_court +
                        newsint2 + factor(state), 
                      data = ces %>% filter(race_wht==1),
                      family="binomial")
reg.inter.dif = glm(approval_sc3 ~ rr*factor(year) +
                      gender_male + age + 
                      educ + faminc_new + 
                      factor(pid3a) + ideo_dif + 
                      newsint2 + factor(state), 
                    data = ces %>% filter(race_wht==1),
                    family="binomial")

# Reg Table: Table 3: Explaining Supreme Court Approval Using the Cooperative Election Survey with Varying Ideology Measures, Logistic Regressions [In body of paper]
texreg(list(reg.inter.self,reg.inter.court,reg.inter.dif),
       omit.coef = "state*",
       custom.coef.map = list("rr"="Racial Resentment",
                              "factor(year)2012"="2012",
                              "factor(year)2014"="2014",
                              "factor(year)2018"="2018",
                              "factor(year)2020"="2020",
                              "ideo_self"="R Ideology",
                              "ideo_court"="Court Ideology",
                              "ideo_dif"="Dif. in Ideology",
                              "rr:factor(year)2012"="RR * 2012",
                              "rr:factor(year)2014"="RR * 2014",
                              "rr:factor(year)2018"="RR * 2018",
                              "rr:factor(year)2020"="RR * 2020"))

# Figure: Figure 5: Predicted Probability of Supreme Court Approval, CES Data with Controlling for Varying Measures of Ideology [In body of paper]
new_wht = data.frame("rr" = rep(seq_rr,5),
                     "year"= c(rep(2010,length(seq_rr)),
                               rep(2012,length(seq_rr)),
                               rep(2014,length(seq_rr)),
                               rep(2018,length(seq_rr)),
                               rep(2020,length(seq_rr))),
                     "gender_male" = round(mean(ces$gender_male[ces$race_wht==1],na.rm=T),0),
                     "age" = mean(ces$age[ces$race_wht==1],na.rm=T),
                     "educ" = mean(ces$educ[ces$race_wht==1],na.rm=T),
                     "faminc_new" = mean(ces$faminc_new[ces$race_wht==1],na.rm=T),
                     "pid3a" = round(mean(ces$pid3a[ces$race_wht==1],na.rm=T),0),
                     "ideo_self" = mean(ces$ideo_self[ces$race_wht==1],na.rm=T),
                     "newsint2" = mean(ces$newsint2[ces$race_wht==1],na.rm=T), 
                     "state" = round(mean(ces$state[ces$race_wht==1],na.rm=T),0))

new_wht2 = data.frame("rr" = rep(seq_rr,3),
                      "year"= c(rep(2012,length(seq_rr)),
                                rep(2014,length(seq_rr)),
                                rep(2018,length(seq_rr))),
                      "gender_male" = round(mean(ces$gender_male[ces$race_wht==1],na.rm=T),0),
                      "age" = mean(ces$age[ces$race_wht==1],na.rm=T),
                      "educ" = mean(ces$educ[ces$race_wht==1],na.rm=T),
                      "faminc_new" = mean(ces$faminc_new[ces$race_wht==1],na.rm=T),
                      "pid3a" = round(mean(ces$pid3a[ces$race_wht==1],na.rm=T),0),
                      "ideo_self" = mean(ces$ideo_self[ces$race_wht==1],na.rm=T),
                      "ideo_court" = mean(ces$ideo_court[ces$race_wht==1],na.rm=T),
                      "ideo_dif" = mean(ces$ideo_dif[ces$race_wht==1],na.rm=T),
                      "newsint2" = mean(ces$newsint2[ces$race_wht==1],na.rm=T), 
                      "state" = round(mean(ces$state[ces$race_wht==1],na.rm=T),0))
tab.wht.self = logit.pred(reg.inter.self,new_wht) %>%
  mutate("Resentment" = rep(seq_rr,5),
         "Year" = factor(c(rep(2010,length(seq_rr)),
                           rep(2012,length(seq_rr)),
                           rep(2014,length(seq_rr)),
                           rep(2018,length(seq_rr)),
                           rep(2020,length(seq_rr)))))
tab.wht.court = logit.pred(reg.inter.court,new_wht2) %>%
  mutate("Resentment" = rep(seq_rr,3),
         "Year" = factor(c(rep(2012,length(seq_rr)),
                           rep(2014,length(seq_rr)),
                           rep(2018,length(seq_rr)))))
tab.wht.dif = logit.pred(reg.inter.dif,new_wht2) %>%
  mutate("Resentment" = rep(seq_rr,3),
         "Year" = factor(c(rep(2012,length(seq_rr)),
                           rep(2014,length(seq_rr)),
                           rep(2018,length(seq_rr)))))

tab.wht.self$yr = tab.wht.self$Year
tab.wht.self$Year = gsub("20","'",tab.wht.self$yr)
tab.wht.dif$yr = tab.wht.dif$Year
tab.wht.dif$Year = gsub("20","'",tab.wht.dif$yr)

fig.ces.selfideo = ggplot(tab.wht.self %>% 
                            filter(yr %in% c(2012,2014,2018)),
                          aes(Resentment,est,linetype=Year)) + 
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.2) +
  geom_line(size=1) + ylim(0,1) +
  theme_bw() + theme(legend.position = "bottom") +
  ylab("Pr(Approval)") + xlab("Racial Resentment") 

fig.ces.courtideo = ggplot(tab.wht.court,
                           aes(Resentment,est,linetype=Year)) + 
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.2) +
  geom_line(size=1) + ylim(0,1) +
  theme_bw() + theme(legend.position = "bottom") +
  ylab("Pr(Approval)") + xlab("Racial Resentment") 

# %>% filter(Year %in% c(2012,2018))
fig.ces.selfdif = ggplot(tab.wht.dif,
                         aes(Resentment,est,linetype=Year)) + 
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.2) +
  geom_line(size=1) + ylim(0,1) +
  theme_bw() + theme(legend.position = "bottom") +
  ylab("Pr(Approval)") + xlab("Racial Resentment")

pdf("Figures/Fig_CESIdeoPr.pdf",8.50,4.03)
cowplot::plot_grid(fig.ces.selfideo,
                   fig.ces.courtideo,
                   fig.ces.selfdif,
                   labels=c("a.","b","c."),
                   nrow=1)
dev.off()

############# Appendix - ANES - Descriptives (All) #############

# Number of respondents 
race.counts.yr = anes.sm %>% 
  group_by(year) %>%
  summarize(Black = sum(race_blk),
            White = sum(race_wht),
            Total = length(race_blk))
race.counts.yr
summary(race.counts.yr)

# Summary
anes.yr.race = anes.sm %>% 
  mutate(race2 = ifelse(race_blk == 1,"Black",
                        ifelse(race_wht == 1, "White",NA))) %>% 
  filter(!is.na(race2)) %>%
  group_by(race2,year2) %>%
  summarize(mean.sc = mean(thermom_sc, na.rm=T),
            sd.sc = sd(thermom_sc, na.rm=T),
            n.sc = sum(!is.na(thermom_sc)),
            mean.cong = mean(ifelse(VCF0228>97,NA,VCF0228),na.rm=T), 
            respondents = sum(!is.na(thermom_sc)),
            mean.rr = mean(thermom_dif2,na.rm=T),
            mean.affinity = mean(thermom_blk,na.rm=T)) %>%
  ungroup() %>%
  mutate(se.sc = sd.sc/sqrt(n.sc),
         year = as.numeric(as.character(year2)),
         Race = race2) %>%
  filter(!is.na(sd.sc))

sum(anes.yr.race$respondents[anes.yr.race$race2=="White"])
sum(anes.yr.race$respondents[anes.yr.race$race2=="Black"])

# Over Time
fig.anes.overtime = ggplot(anes.yr.race, 
                           aes(year,mean.sc,
                               linetype=Race,shape=Race)) +
  geom_point(size=3) + geom_smooth(color="black") + theme_bw(base_size=9) +
  ylab("Mean Feelings Toward\nthe Supreme Court") + 
  xlab("Year") + theme(legend.position = "bottom")
fig.anes.overtime

pdf("Figures/ANES_Overtime.pdf", 5.82,3.88)
fig.anes.overtime
dev.off()

#############  Appendix - ANES - Descriptives, White Respondent Only #############

# Correlations
cor80 = cor(anes.sm %>% filter(race_wht == 1 & year == 1980) %>% 
              select(rr,thermom_dif2,thermom_sc,ideo), 
            use = "pairwise.complete.obs")
cor80.df = tidyr::gather(data.frame(cbind(rownames(cor80),cor80)), 
                         V2, value, rr:ideo, factor_key=TRUE) %>%
  filter(!is.na(value)) %>%
  mutate(year = 1980)
cor88 = cor(anes.sm %>% filter(race_wht == 1 & year == 1988) %>% 
              select(rr,thermom_dif2,thermom_sc,ideo), 
            use = "pairwise.complete.obs")
cor88.df = tidyr::gather(data.frame(cbind(rownames(cor88),cor88)), 
                         V2, value, rr:ideo, factor_key=TRUE) %>%
  filter(!is.na(value)) %>%
  mutate(year = 1988)
cor00 = cor(anes.sm %>% filter(race_wht == 1 & year == 2000) %>% 
              select(rr,thermom_dif2,thermom_sc,ideo), 
            use = "pairwise.complete.obs")
cor00.df = tidyr::gather(data.frame(cbind(rownames(cor00),cor00)), 
                         V2, value, rr:ideo, factor_key=TRUE) %>%
  filter(!is.na(value)) %>%
  mutate(year = 2000)
cor20 = cor(anes.sm %>% filter(race_wht == 1 & year == 2020) %>% 
              select(rr,thermom_dif2,thermom_sc,ideo), 
            use = "pairwise.complete.obs")
cor20.df = tidyr::gather(data.frame(cbind(rownames(cor20),cor20)), 
                         V2, value, rr:ideo, factor_key=TRUE) %>%
  filter(!is.na(value)) %>%
  mutate(year = 2020)
colnames(cor80) = rownames(cor80) = c("Racial\nResenment","White-Black",
                                      "Supreme\nCourt Feelings", "Ideology")
colnames(cor88) = rownames(cor88) = c("Racial\nResenment","White-Black",
                                      "Supreme\nCourt Feelings", "Ideology")
colnames(cor00) = rownames(cor00) = c("Racial\nResenment","White-Black",
                                      "Supreme\nCourt Feelings", "Ideology")
colnames(cor20) = rownames(cor20) = c("Racial\nResenment","White-Black",
                                      "Supreme\nCourt Feelings", "Ideology")

cor.df = bind_rows(cor80.df,cor88.df,cor00.df,cor20.df)

# Cleveland plot
for.cleveland.plot = cor.df %>% mutate(top = ifelse(V1 == "thermom_dif2",3,
                                                    ifelse(V1 == "thermom_sc",1,
                                                           ifelse(V1 == "ideo",4,2))),
                                       bottom = ifelse(V2 == "thermom_dif2",3,
                                                       ifelse(V2 == "thermom_sc",1,
                                                              ifelse(V2 == "ideo",4,2))),
                                       top = factor(top, levels=1:4, 
                                                    labels=c("Supreme Court Thermometer",
                                                             "Racial Resentment",
                                                             "Racial Animus",
                                                             "Ideology")),
                                       bottom = factor(bottom, levels=1:4, 
                                                       labels=c("Supreme Court Thermom.",
                                                                "Racial Resentment",
                                                                "Racial Animus",
                                                                "Ideology")))


# FIGURE: Figure 5: Cleveland Plot of the Correlations between the Supreme Court Thermometer or Racial Resentment and Ideology and Racial Animus Over Time (ANES) [Appendix]
fig.anes.cleveland = ggplot(for.cleveland.plot %>% 
                              filter(year==1980|year==1988|year==2020) %>%
                              filter(V1=="ideo"|V1=="thermom_sc") %>%
                              filter(value != 1), 
                            aes(as.numeric(value),bottom,shape=factor(year))) + 
  geom_vline(xintercept = 0,color="darkgrey") +
  geom_point(size=4) + facet_grid(~top) +
  geom_line(aes(group = bottom),size=1) +
  xlab(NULL) + ylab(NULL) + xlim(-0.5,1) +
  guides(shape=guide_legend(title="Year")) +
  theme_bw(base_size = 14) +
  theme(legend.position = "bottom",
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank())

pdf(file="Figures/Fig_ANES_ClevelandCorr.pdf",9,3.85)
fig.anes.cleveland
dev.off()

# N by Race and Year: Table 4: N by Year and Respondent Race, ANES [Appendix]
anes.n.race.yr = anes.sm %>% group_by(year) %>%
  summarize(White = sum(race_wht),
            Black = sum(race_blk))
xtable(anes.n.race.yr,digits = 0)

# Descriptive Statistics: Table 5: Descriptive Statistics of White Respondents, ANES [Appendix ]
anes.summary = summary.function(variables = anes.sm %>% 
                                  filter(race_wht==1) %>%
                                  mutate(dem = ifelse(pid3 == "1 Democrat",1,0),
                                         inde = ifelse(pid3=="0 Independents",1,0),
                                         rep = ifelse(pid3 == "2 Republican",1,0)) %>%
                                  select(thermom_sc,rr,thermom_dif2,
                                         woman,age,income,education,
                                         dem,inde,rep,ideo,
                                         election_int,govt_trust),
                                names = c("Feelings about the Court","RR Scale","White-Black Feelings",
                                          "Woman","Age","Income","Education",
                                          "Democrat","Indepdent","Republican","Ideology (7)",
                                          "Election Interest","Trust in Government"))

xtable(anes.summary)

############# Appendix - ANES - Full Tables ############# 

# Regressions: 
anes.sm.dem = anes.sm %>% filter(race_wht == 1 & pid3 == "1 Democrat")
reg.anes.wht2.dem = lm(thermom_sc ~ thermom_dif2*year2+
                         govt_trust + age + woman + 
                         income + education +
                         ideo +  election_int,
                       data = anes.sm.dem,
                       weights = anes.sm.dem$VCF0009z)
reg.anes.wht2rr.dem = lm(thermom_sc ~ rr*year2+
                           govt_trust + age + woman + 
                           income + education +
                           ideo +  election_int,
                         data = anes.sm.dem,
                         weights = anes.sm.dem$VCF0009z)

anes.sm.rep = anes.sm %>% filter(race_wht == 1 & pid3 == "2 Republican")
reg.anes.wht2.rep = lm(thermom_sc ~ thermom_dif2*year2+
                         govt_trust + age + woman + 
                         income + education +
                         ideo +  election_int,
                       data = anes.sm.rep,
                       weights = anes.sm.rep$VCF0009z)
reg.anes.wht2rr.rep = lm(thermom_sc ~ rr*year2+
                           govt_trust + age + woman + 
                           income + education +
                           ideo +  election_int,
                         data = anes.sm.rep,
                         weights = anes.sm.rep$VCF0009z)
reg.anes.wht2rr.rep = lm(thermom_sc ~ rr+year2+
                           govt_trust + age + woman + 
                           income + education +
                           ideo +  election_int,
                         data = anes.sm.rep,
                         weights = anes.sm.rep$VCF0009z)

# Full Regression Table: Table 6: OLS Regressions Explaining Feelings Toward the Supreme Court, Overall and by Party Affiliation, ANES 1984 to 2020 [Appendix]
texreg(list(reg.anes.wht2,reg.anes.wht2.dem,reg.anes.wht2.rep,
            reg.anes.wht2rr,reg.anes.wht2rr.dem,reg.anes.wht2rr.rep),stars=0.05,
       custom.model.names = c("M1 - All","M2 - Dem","M3 - Rep","M4 - All","M5 - Dem","M6 - Rep"),
       custom.coef.map = list("(Intercept)"="(Intercept)",
                              "thermom_dif2"="Feelings Toward White-Black People",
                              "rr"="Racial Resentment",
                              "year21984"="1984",
                              "year21988"="1988",
                              "year21996"="1996",
                              "year22000"="2000",
                              "year22004"="2004",
                              "year22008"="2008",
                              "year22012"="2012",
                              "year22016"="2016",
                              "year22020"="2020",
                              "thermom_dif2:year21984"="1984*Racial Attitude",
                              "thermom_dif2:year21988"="1988*Racial Attitude",
                              "thermom_dif2:year21996"="1996*Racial Attitude",
                              "thermom_dif2:year22000"="2000*Racial Attitude",
                              "thermom_dif2:year22004"="2004*Racial Attitude",
                              "thermom_dif2:year22008"="2008*Racial Attitude",
                              "thermom_dif2:year22012"="2012*Racial Attitude",
                              "thermom_dif2:year22016"="2016*Racial Attitude",
                              "thermom_dif2:year22020"="2020*Racial Attitude",
                              "rr:year21984"="1984*Racial Attitude",
                              "rr:year21988"="1988*Racial Attitude",
                              "rr:year21996"="1996*Racial Attitude",
                              "rr:year22000"="2000*Racial Attitude",
                              "rr:year22004"="2004*Racial Attitude",
                              "rr:year22008"="2008*Racial Attitude",
                              "rr:year22012"="2012*Racial Attitude",
                              "rr:year22016"="2016*Racial Attitude",
                              "rr:year22020"="2020*Racial Attitude",
                              "govt_trust"="Government Trust",
                              "age"="Age","woman"="Woman",
                              "income"="Income",
                              "education"="Education",
                              "pid31 Democrat"="Democrat",
                              "pid32 Republican"="Republican",
                              "ideo"="Ideology",
                              "election_int"="Interest in the Election"))

# Predictions. 
n.wht = length(-97:97)
n.wht.seq = -97:97
newdata.wht.full = data.frame("thermom_dif2"=rep(n.wht.seq,11)/100,
                              "year2"=factor(c(rep(1980,n.wht),
                                               rep(1984,n.wht),
                                               rep(1988,n.wht),
                                               rep(1996,n.wht),
                                               rep(2000,n.wht),
                                               rep(2000,n.wht),
                                               rep(2004,n.wht),
                                               rep(2008,n.wht),
                                               rep(2012,n.wht),
                                               rep(2016,n.wht),
                                               rep(2020,n.wht))),
                              "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                              "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                              "woman"=1,
                              "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                              "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                              "pid3"="2 Republican",
                              "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                              "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T))
rr.seq = seq(0,1,by=0.1)
rr.seq.length = length(rr.seq)
newdata.wht.rr.full = data.frame("rr"=rep(rr.seq,8),
                                 "year2"=factor(c(rep(1988,rr.seq.length),
                                                  rep(2000,rr.seq.length),
                                                  rep(2000,rr.seq.length),
                                                  rep(2004,rr.seq.length),
                                                  rep(2008,rr.seq.length),
                                                  rep(2012,rr.seq.length),
                                                  rep(2016,rr.seq.length),
                                                  rep(2020,rr.seq.length))),
                                 "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                                 "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                                 "woman"=1,
                                 "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                                 "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                                 "pid3"="2 Republican",
                                 "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                                 "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T))
pred.wht.full = predict(reg.anes.wht2,
                        newdata = newdata.wht.full,
                        interval="prediction",
                        se.fit=T)
newdata.wht.full$mean = pred.wht.full$fit[,1]
newdata.wht.full$lower = pred.wht.full$fit[,1] - 1.96*pred.wht.full$se.fit
newdata.wht.full$upper = pred.wht.full$fit[,1] + 1.96*pred.wht.full$se.fit

pred.wht.rr.full = predict(reg.anes.wht2rr,
                           newdata = newdata.wht.rr.full,
                           interval="prediction",
                           se.fit=T)
newdata.wht.rr.full$mean = pred.wht.rr.full$fit[,1]
newdata.wht.rr.full$lower = pred.wht.rr.full$fit[,1] - 1.96*pred.wht.rr.full$se.fit
newdata.wht.rr.full$upper = pred.wht.rr.full$fit[,1] + 1.96*pred.wht.rr.full$se.fit

# The figure: Figure 2: Predicted Values of Feelings Toward the Supreme Court by Year and Racial Attitude [Appendix]
cbp2 <- c("#000000", "#E69F00", "#56B4E9", "#009E73",
          "#F0E442", "#0072B2", "#D55E00", "#CC79A7",
          "#999999","#009E73",)

fig.pred.prob.wht.full = ggplot(newdata.wht.full, 
                                aes(thermom_dif2,mean,
                                    linetype=year2,color=year2)) + 
  geom_line(size=1) + 
  theme_bw(base_size = 10) +
  theme(legend.position = "bottom") +
  guides(color=guide_legend(title="Year"),
         linetype=guide_legend(title="Year")) +
  xlab("White - Black Feelings \nThermometer") +
  ylab("Feelings Toward the \nSupreme Court") + 
  ylim(0,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)

fig.pred.prob.wht.rr.full = ggplot(newdata.wht.rr.full, 
                                   aes(rr,mean,linetype=year2,color=year2)) + 
  geom_line(size=1) + 
  theme_bw(base_size = 10) +
  theme(legend.position = "bottom") +
  guides(color=guide_legend(title="Year"),
         linetype=guide_legend(title="Year")) +
  xlab("Racial Resentment Scale") +
  ylab("Feelings Toward the \nSupreme Court") + 
  ylim(0,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)

cowplot::plot_grid(fig.pred.prob.wht.full,
                   fig.pred.prob.wht.rr.full,
                   labels=c("a.","b."))

# Saving the figure. 
pdf("Figures/Fig_ANES_PredProb_WhiteRespOnly_Full.pdf",8,4.2)
cowplot::plot_grid(fig.pred.prob.wht.full,
                   fig.pred.prob.wht.rr.full,
                   labels=c("a.","b."))
dev.off()


#########  ANES -- Same Cohort Table - Appendix #########

# Same Cohort:
reg.anes.wht2.old = lm(thermom_sc ~ thermom_dif2*year2+
                         govt_trust + age + woman + 
                         income + education +
                         pid3 + ideo +  election_int,
                       data = anes.sm %>% 
                         filter(race_wht == 1 & 
                                  birth.yr>1942 & birth.yr <1963))
reg.anes.wht2rr.old = lm(thermom_sc ~ rr*year2+
                           govt_trust + age + woman + 
                           income + education +
                           pid3 + ideo +  election_int,
                         data = anes.sm %>% 
                           filter(race_wht == 1 & 
                                    birth.yr>1942 & birth.yr <1963))

# Reg Table:  Table 8: OLS Regressions Explaining Feelings Toward the Supreme Court, Overall and for a Single Cohort [In appendix]
texreg(list(reg.anes.wht2, reg.anes.wht2.old,
            reg.anes.wht2rr,reg.anes.wht2rr.old),stars=0.05,
       custom.coef.map = list("(Intercept)"="(Intercept)",
                              "thermom_dif2"="Feelings Toward White-Black People",
                              "rr"="Racial Resentment",
                              "year21984"="1984",
                              "year21988"="1988",
                              "year21996"="1996",
                              "year22000"="2000",
                              "year22004"="2004",
                              "year22008"="2008",
                              "year22012"="2012",
                              "year22016"="2016",
                              "year22020"="2020",
                              "thermom_dif2:year21984"="1984*Racial Attitude",
                              "thermom_dif2:year21988"="1988*Racial Attitude",
                              "thermom_dif2:year21996"="1996*Racial Attitude",
                              "thermom_dif2:year22000"="2000*Racial Attitude",
                              "thermom_dif2:year22004"="2004*Racial Attitude",
                              "thermom_dif2:year22008"="2008*Racial Attitude",
                              "thermom_dif2:year22012"="2012*Racial Attitude",
                              "thermom_dif2:year22016"="2016*Racial Attitude",
                              "thermom_dif2:year22020"="2020*Racial Attitude",
                              #"rr:year21984"="1984*Racial Attitude",
                              #"rr:year21988"="1988*Racial Attitude",
                              #"rr:year21996"="1996*Racial Attitude",
                              "rr:year22000"="2000*Racial Attitude",
                              "rr:year22004"="2004*Racial Attitude",
                              "rr:year22008"="2008*Racial Attitude",
                              "rr:year22012"="2012*Racial Attitude",
                              "rr:year22016"="2016*Racial Attitude",
                              "rr:year22020"="2020*Racial Attitude"))


#########  ANES -- LGBT ############

reg.anes.lgbt = lm(thermom_sc ~ thermom_lgbt*year2+
                     govt_trust + age + woman + 
                     income + education +
                     pid3 + ideo +  election_int,
                   data = anes.sm %>% 
                     filter(race_wht == 1),
                   weights = anes.sm$VCF0009z[anes.sm$race_wht==1])

# Reg Table: Table 11: OLS Regressions Explaining Feelings Toward the Supreme Court, Attitudes Towards “Gays and Lesbians” [In appendix]

texreg(list(reg.anes.wht2,reg.anes.wht2rr,reg.anes.lgbt),stars=0.05,
       custom.model.names = c("Model 1","Model 2","Model 3"),
       custom.coef.map = list("(Intercept)"="(Intercept)",
                              "thermom_dif2"="Feelings Toward White-Black People",
                              "rr"="Racial Resentment",
                              "thermom_lgbt" = "Feelings Toward Gays and Lesbians People",
                              "year21984"="1984",
                              "year21988"="1988",
                              "year21996"="1996",
                              "year22000"="2000",
                              "year22004"="2004",
                              "year22008"="2008",
                              "year22012"="2012",
                              "year22016"="2016",
                              "year22020"="2020",
                              "thermom_dif2:year21984"="1984*Group Based Attitude",
                              "thermom_dif2:year21988"="1988*Group Based Attitude",
                              "thermom_dif2:year21996"="1996*Group Based Attitude",
                              "thermom_dif2:year22000"="2000*Group Based Attitude",
                              "thermom_dif2:year22004"="2004*Group Based Attitude",
                              "thermom_dif2:year22008"="2008*Group Based Attitude",
                              "thermom_dif2:year22012"="2012*Group Based Attitude",
                              "thermom_dif2:year22016"="2016*Group Based Attitude",
                              "thermom_dif2:year22020"="2020*Group Based Attitude",
                              "rr:year22000"="2000*Group Based Attitude",
                              "rr:year22004"="2004*Group Based Attitude",
                              "rr:year22008"="2008*Group Based Attitude",
                              "rr:year22012"="2012*Group Based Attitude",
                              "rr:year22016"="2016*Group Based Attitude",
                              "rr:year22020"="2020*Group Based Attitude",
                              "thermom_lgbt:year21988"="1988*Group Based Attitude",
                              "thermom_lgbt:year21996"="1996*Group Based Attitude",
                              "thermom_lgbt:year22000"="2000*Group Based Attitude",
                              "thermom_lgbt:year22004"="2004*Group Based Attitude",
                              "thermom_lgbt:year22008"="2008*Group Based Attitude",
                              "thermom_lgbt:year22012"="2012*Group Based Attitude",
                              "thermom_lgbt:year22016"="2016*Group Based Attitude",
                              "thermom_lgbt:year22020"="2020*Group Based Attitude",
                              "govt_trust"="Government Trust",
                              "age"="Age","woman"="Woman",
                              "income"="Income",
                              "education"="Education",
                              "pid31 Democrat"="Democrat",
                              "pid32 Republican"="Republican",
                              "ideo"="Ideology",
                              "election_int"="Interest in the Election"))

# Figure: Figure 3: Predicted Values of Feelings Toward the Supreme Court by Feelings Toward LG People and Year (ANES) [In appendix]
n.lgbt = length(0:99)
newdata.lgbt = data.frame("thermom_lgbt"=c(0:99,0:99,0:99,0:99)/100,
                          "year2"=factor(c(rep(1984,n.lgbt),
                                           rep(2000,n.lgbt),
                                           rep(2016,n.lgbt),
                                           rep(2020,n.lgbt))),
                          "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                          "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                          "woman"=1,
                          "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                          "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                          "pid3"="2 Republican",
                          "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                          "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T))
pred.lgbt = predict(reg.anes.lgbt,
                    newdata = newdata.lgbt,
                    interval="prediction",
                    se.fit=T)
newdata.lgbt$mean = pred.lgbt$fit[,1]
newdata.lgbt$lower = pred.lgbt$fit[,1] - 1.96*pred.lgbt$se.fit
newdata.lgbt$upper = pred.lgbt$fit[,1] + 1.96*pred.lgbt$se.fit

pdf("Figures/Fig_ANES_PredProb_LGBT_WhiteRespOnly.pdf",5.54,4.73)
ggplot(newdata.lgbt, 
       aes(thermom_lgbt,mean,linetype=year2,color=year2)) + 
  geom_line(linewidth=1) + 
  theme_bw(base_size = 12) +
  theme(legend.position = "bottom") +
  guides(color=guide_legend(title="Year"),
         linetype=guide_legend(title="Year")) +
  xlab("Feelings Thermometer: LGBT") +
  ylab("Feelings Toward the \nSupreme Court") + 
  ylim(0,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)
dev.off()






############# Appendix - ANES - Affirmative Action ############# 

# ANES Regressions
anes.sm$affirm.action = ifelse(anes.sm$VCF0867 == 5, 0,
                               ifelse(anes.sm$VCF0867 == 1, 1, NA))
reg.anes.aa = lm(thermom_sc ~ thermom_dif2*year2+
                   govt_trust + age + woman + 
                   income + education +
                   affirm.action+ pid3 + 
                   ideo +  election_int,
                 data = anes.sm %>% 
                   filter(race_wht == 1),
                 weights = anes.sm$VCF0009z[anes.sm$race_wht==1])
reg.anes.aa.rr = lm(thermom_sc ~ rr*year2+
                      govt_trust + age + woman + 
                      income + education +
                      affirm.action+ pid3 + 
                      ideo +  election_int,
                    data = anes.sm %>% 
                      filter(race_wht == 1),
                    weights = anes.sm$VCF0009z[anes.sm$race_wht==1])

# Reg. Table:Table 9: OLS Regressions Explaining Feelings Toward the Supreme Court, Controlling for Opinions on Affirmative Action [In appendix]
texreg(list(reg.anes.aa,reg.anes.aa.rr), 
       custom.coef.map = list("(Intercept)"="(Intercept)",
                              "thermom_dif2"="Feelings Toward White-Black People",
                              "rr"="Racial Resentment",
                              "year22000"="2000",
                              "year22004"="2004",
                              "year22008"="2008",
                              "year22012"="2012",
                              "year22016"="2016",
                              "year22020"="2020",
                              "thermom_dif2:year22000"="2000*Racial Attitude",
                              "thermom_dif2:year22004"="2004*Racial Attitude",
                              "thermom_dif2:year22008"="2008*Racial Attitude",
                              "thermom_dif2:year22012"="2012*Racial Attitude",
                              "thermom_dif2:year22016"="2016*Racial Attitude",
                              "thermom_dif2:year22020"="2020*Racial Attitude",
                              #"rr:year21984"="1984*Racial Attitude",
                              #"rr:year21988"="1988*Racial Attitude",
                              #"rr:year21996"="1996*Racial Attitude",
                              "rr:year22000"="2000*Racial Attitude",
                              "rr:year22004"="2004*Racial Attitude",
                              "rr:year22008"="2008*Racial Attitude",
                              "rr:year22012"="2012*Racial Attitude",
                              "rr:year22016"="2016*Racial Attitude",
                              "rr:year22020"="2020*Racial Attitude",
                              "affirm.action" = "Affirmative Action Support",
                              "ideo" = "Ideology"))

# Predictions. 
n.wht = length(-97:97)
newdata.wht = data.frame("thermom_dif2"=c(-97:97,-97:97)/100,
                         "year2"=factor(c(rep(2000,n.wht),
                                          rep(2020,n.wht))),
                         "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                         "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                         "woman"=1,
                         "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                         "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                         "pid3"="2 Republican",
                         "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                         "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T),
                         "affirm.action"=mean(anes.sm$affirm.action[anes.sm$race_wht==1],na.rm=T))
newdata.wht.rr = data.frame("rr"=c(seq(0,1,by=0.1),seq(0,1,by=0.1)),
                            "year2"=factor(c(rep(2000,length(seq(0,1,by=0.1))),
                                             rep(2020,length(seq(0,1,by=0.1))))),
                            "govt_trust"=mean(anes.sm$govt_trust[anes.sm$race_wht==1],na.rm=T),
                            "age"=mean(anes.sm$age[anes.sm$race_wht==1],na.rm=T),
                            "woman"=1,
                            "income"=mean(anes.sm$income[anes.sm$race_wht==1],na.rm=T),
                            "education"=mean(anes.sm$education[anes.sm$race_wht==1],na.rm=T),
                            "pid3"="2 Republican",
                            "ideo" = mean(anes.sm$ideo[anes.sm$race_wht==1],na.rm=T),
                            "election_int"=mean(anes.sm$election_int[anes.sm$race_wht==1],na.rm=T),
                            "affirm.action"=mean(anes.sm$affirm.action[anes.sm$race_wht==1],na.rm=T))
pred.wht = predict(reg.anes.aa,
                   newdata = newdata.wht,
                   interval="prediction",
                   se.fit=T)
newdata.wht$mean = pred.wht$fit[,1]
newdata.wht$lower = pred.wht$fit[,1] - 1.96*pred.wht$se.fit
newdata.wht$upper = pred.wht$fit[,1] + 1.96*pred.wht$se.fit

pred.wht.rr = predict(reg.anes.aa.rr,
                      newdata = newdata.wht.rr,
                      interval="prediction",
                      se.fit=T)
newdata.wht.rr$mean = pred.wht.rr$fit[,1]
newdata.wht.rr$lower = pred.wht.rr$fit[,1] - 1.96*pred.wht.rr$se.fit
newdata.wht.rr$upper = pred.wht.rr$fit[,1] + 1.96*pred.wht.rr$se.fit

# The figures
fig.pred.prob.wht = ggplot(newdata.wht, aes(thermom_dif2,mean,linetype=year2)) + 
  geom_line(size=1) + 
  theme_bw(base_size = 12) +
  theme(legend.position = "bottom") +
  guides(color=guide_legend(title="Year"),
         linetype=guide_legend(title="Year")) +
  scale_color_manual(values=cbp2) +
  xlab("White - Black Feelings \nThermometer") +
  ylab("Feelings Toward the \nSupreme Court") + 
  ylim(0,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)

fig.pred.prob.wht.rr = ggplot(newdata.wht.rr, aes(rr,mean,linetype=year2)) + 
  geom_line(size=1) + 
  theme_bw(base_size = 12) +
  theme(legend.position = "bottom") +
  guides(color=guide_legend(title="Year"),
         linetype=guide_legend(title="Year")) +
  scale_color_manual(values=cbp2) +
  xlab("Racial Resentment Scale") +
  ylab("Feelings Toward the \nSupreme Court") + 
  ylim(0,100)+
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.1, colour = NA)

cowplot::plot_grid(fig.pred.prob.wht,
                   fig.pred.prob.wht.rr,
                   labels=c("a.","b."))

# Saving the figure. 
pdf("Figures/Fig_ANES_PredProb_AA_WhiteRespOnly.pdf",7.49,4.03)
cowplot::plot_grid(fig.pred.prob.wht,fig.pred.prob.wht.rr,
                   labels=c("a.","b."))
dev.off()


#############  Court Salience - Appendix ############# 
### see estimates from Table 2 in body of the paper 

# Table 7: OLS Regressions Explaining Feelings Toward the Supreme Court, Difference in Salience of Court Decisions on Racial & Racialized Civil Rights Cases (ANES 1980 to 2020)
texreg(list(reg.salience.wht2,reg.salience.wht2rr),stars=0.05,
       custom.coef.map = list("(Intercept)"="(Intercept)",
                              "thermom_dif2"="Feelings Toward White-Black People",
                              "rr"="Racial Resentment",
                              "decision_salience"="Salience Difference",
                              "thermom_dif2:decision_salience"="Salience Difference*Racial Attitude",
                              "rr:decision_salience"="Salience Difference*Racial Attitude",
                              "govt_trust"="Government Trust",
                              "age"="Age","woman"="Woman",
                              "income"="Income",
                              "education"="Education",
                              "pid31 Democrat"="Democrat",
                              "pid32 Republican"="Republican",
                              "ideo"="Ideology",
                              "election_int"="Interest in the Election"))

############# Appendix - CES ############# 

# Descriptive Statistics: Table 12: Descriptive Statistics of White Respondents, CES [Appendix]
ces.summary = summary.function(variables = ces %>% 
                                 filter(race_wht==1) %>%
                                 mutate(dem = ifelse(pid3a == 1,1,0),
                                        inde = ifelse(pid3==0,1,0),
                                        rep = ifelse(pid3 == 2,1,0)) %>%
                                 select(approval_sc3,rr,
                                        ideo_self,ideo_court,ideo_dif,
                                        gender_male,age,faminc_new,educ,
                                        dem,inde,rep,
                                        newsint2),
                               names = c("Court Approval","Racial Resentment",
                                         "Ideology, Self","Ideology, Court","Ideology, Difference",
                                         "Man","Age","Income","Education",
                                         "Democrat","Indepdent","Republican",
                                         "Interest in Politics"))

xtable(ces.summary)

# Full Table: Table 13: Explaining Supreme Court Approval Using the Cooperative Election Survey with Varying Ideology Measures, Logistic Regressions [in appendix]
texreg(list(reg.inter.self,reg.inter.court,reg.inter.dif),
       omit.coef = "state*",
       custom.coef.map = list("rr"="Racial Resentment",
                              "factor(year)2012"="2012",
                              "factor(year)2014"="2014",
                              "factor(year)2018"="2018",
                              "factor(year)2020"="2020",
                              "ideo_self"="R Ideology",
                              "ideo_court"="Court Ideology",
                              "ideo_dif"="Dif. in Ideology",
                              "rr:factor(year)2012"="RR * 2012",
                              "rr:factor(year)2014"="RR * 2014",
                              "rr:factor(year)2018"="RR * 2018",
                              "rr:factor(year)2020"="RR * 2020",
                              "gender_male"="Male","age"="Age",
                              "educ"="Education",
                              "faminc_new"="Family Income",
                              "factor(pid3a)1"="Democrat",
                              "factor(pid3a)2"="Republican",
                              "newsint2"="Interest in Politics"))

# Full Figure: Figure 4: Predicted Probability of Supreme Court Approval, CES Data with Controlling for Varying Measures of Ideology [in appendix]
fig.ces.selfideo.full = ggplot(tab.wht.self,
                               aes(Resentment,est,linetype=Year,color=Year)) + 
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.2) +
  geom_line(size=1) + ylim(0,1) +
  theme_bw(base_size=10) + theme(legend.position = "bottom") +
  ylab("Pr(Approval)") + xlab("Racial Resentment") 

fig.ces.courtideo.full = ggplot(tab.wht.court,
                                aes(Resentment,est,linetype=Year,color=Year)) + 
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.2) +
  geom_line(size=1) + ylim(0,1) +
  theme_bw(base_size=10) + theme(legend.position = "bottom") +
  ylab("Pr(Approval)") + xlab("Racial Resentment") 

# %>% filter(Year %in% c(2012,2018))
fig.ces.selfdif.full = ggplot(tab.wht.dif,
                              aes(Resentment,est,linetype=Year,color=Year)) + 
  geom_ribbon(aes(ymin=lower, ymax=upper), 
              alpha=0.2) +
  geom_line(size=1) + ylim(0,1) +
  theme_bw(base_size=10) + theme(legend.position = "bottom") +
  ylab("Pr(Approval)") + xlab("Racial Resentment")

pdf("Figures/Fig_CESIdeoPr_Full.pdf",10,4.5)
cowplot::plot_grid(fig.ces.selfideo.full,
                   fig.ces.courtideo.full,
                   fig.ces.selfdif.full,
                   labels=c("a.","b","c."),
                   nrow=1)
dev.off()

############# Appendix - CES - Cor.############# 


cor(ces %>% filter(year == 2010) %>%
      select(rr,ideo_self,ideo_court,ideo_dif),
    use="pairwise.complete.obs")

cor(ces %>% filter(year == 2012) %>%
      select(rr,ideo_self,ideo_court,ideo_dif),
    use="pairwise.complete.obs")

cor(ces %>% filter(year == 2014) %>%
      select(rr,ideo_self,ideo_court,ideo_dif),
    use="pairwise.complete.obs")

cor(ces %>% filter(year == 2018) %>%
      select(rr,ideo_self,ideo_court,ideo_dif),
    use="pairwise.complete.obs")

cor(ces %>% filter(year == 2020) %>%
      select(rr,ideo_self,ideo_court,ideo_dif),
    use="pairwise.complete.obs")

#    Figure 6: Correlations between Ideology and Racial Resentment by Year, CES [in appendix]

pdf(file="Figures/CES-Cor2010.pdf",4.61,4.34)
cor2010 = corrplot::corrplot(cor(ces %>% filter(year == 2010) %>%
                                   select(rr,ideo_self,
                                          ideo_court,ideo_dif),
                                 use="pairwise.complete.obs"), 
                             addCoef.col="black")
dev.off()
pdf(file="Figures/CES-Cor2012.pdf",4.61,4.34)
cor2012 = corrplot::corrplot(cor(ces %>% filter(year == 2012) %>%
                                   select(rr,ideo_self,
                                          ideo_court,ideo_dif),
                                 use="pairwise.complete.obs"), 
                             addCoef.col="black")
dev.off()
pdf(file="Figures/CES-Cor2014.pdf",4.61,4.34)
cor2014 = corrplot::corrplot(cor(ces %>% filter(year == 2014) %>%
                                   select(rr,ideo_self,
                                          ideo_court,ideo_dif),
                                 use="pairwise.complete.obs"), 
                             addCoef.col="black")
dev.off()
pdf(file="Figures/CES-Cor2016.pdf",4.61,4.34)
cor2016 = corrplot::corrplot(cor(ces %>% filter(year == 2016) %>%
                                   select(rr,ideo_self,
                                          ideo_court,ideo_dif),
                                 use="pairwise.complete.obs"), 
                             addCoef.col="black")
dev.off()
pdf(file="Figures/CES-Cor2018.pdf",4.61,4.34)
cor2018 = corrplot::corrplot(cor(ces %>% filter(year == 2018) %>%
                                   select(rr,ideo_self,
                                          ideo_court,ideo_dif),
                                 use="pairwise.complete.obs"), 
                             addCoef.col="black")
dev.off()
pdf(file="Figures/CES-Cor2020.pdf",4.61,4.34)
cor2020 = corrplot::corrplot(cor(ces %>% filter(year == 2020) %>%
                                   select(rr,ideo_self,
                                          ideo_court,ideo_dif),
                                 use="pairwise.complete.obs"), 
                             addCoef.col="black")
dev.off()

############# Appendix - YouGov - Cleaning #############

# Data
kbj <- read_sav("Data/UNSC0003_OUTPUT.sav")

# Cleaning the dat set.
kbj = kbj %>% mutate(
  positive_attr = ifelse(SCS027_1 == 1, 1, 0) +
    ifelse(SCS027_2 == 1, 1, 0) +
    ifelse(SCS027_3 == 1, 1, 0) +
    ifelse(SCS027_4 == 1, 1, 0),
  negative_attr = ifelse(SCS027_5 == 1, 1, 0) +
    ifelse(SCS027_6 == 1, 1, 0) +
    ifelse(SCS027_7 == 1, 1, 0),
  dif_attr = positive_attr - negative_attr,
  all_attr = positive_attr + negative_attr,
  rr1 = (SCS003 - 6) * -1,
  rr_scale = (((rr1 + SCS004) / 2)-1)/4,
  IRmarriage_approve = SCS029,
  linked_fate = (((SCS005 - 5) * -1)-1)/3,
  discrim = (SCS006 - 3) * -1,
  kbj_hearings_watch = (SCS023 - 5) * -1,
  kbj_fair = ifelse(SCS026==3,NA,ifelse(SCS026==1,1,0)),
  kbj_rep = ifelse(SCS028>5,NA,(SCS028-6)*-1),
  kbj_approval = ifelse(SCS031_f==3,NA,ifelse(SCS031_f==1,1,0)),
  kamala_approval = ifelse(SCS031_e==3,NA,ifelse(SCS031_e==1,1,0)),
  sc_approval = ifelse(SCS031_a==3,NA,ifelse(SCS031_a==1,1,0)),
  dif_women_approval = kbj_approval - kamala_approval,
  dif_sc_approval = kbj_approval - sc_approval,
  age = 2022 - birthyr, 
  pid = ifelse(pid7 %in% 1:3,"Dem",
               ifelse(pid7==4,"Inde",
                      ifelse(pid7 %in% 5:7,"Rep",NA))),
  presvote220 = ifelse(presvote20post==6,0,1),
  hearings = (SCS023-4)*-1,
  ideo = ifelse(ideo5>5,NA,ideo5)
)

############# Appendix - YouGov - White Respondent Descriptives + Analysis ###############

# Counts and what not.
table(kbj$SCS001)

kbj.white.resp =kbj %>% 
  filter(SCS001 == 1) %>%
  mutate(sc_approval2 = ifelse(sc_approval==1,"Yes","No"))

prop.table(table(kbj.white.resp$sc_approval))
table(kbj.white.resp$sc_approval)
table(is.na(kbj.white.resp$sc_approval))
summary(kbj.white.resp$rr_scale)

# Figures: Figure 1: Summarizing Court Approval and Racial Resentment (In appendix)
# Summarizing white respondents only.
fig.rr.hist = ggplot(kbj %>% 
                       filter(SCS001 == 1 & !is.na(sc_approval)) %>%
                       mutate(sc_approval2 = ifelse(sc_approval==1,"Yes","No")), 
                     aes(rr_scale)) + geom_histogram(binwidth = 0.125) + 
  ylab("Frequency") + 
  xlab("Racial Resentment Scale") +
  theme_bw(base_size = 13)

fig.approval.bar = ggplot(kbj %>% 
                            filter(SCS001 == 1 & !is.na(sc_approval)) %>%
                            mutate(sc_approval2 = ifelse(sc_approval==1,"Yes","No")), 
                          aes(sc_approval2)) + geom_bar() + 
  ylab("Frequency") + 
  xlab("Approve of the Court?") +
  theme_bw(base_size = 13)

fig.sc.violin = ggplot(kbj %>% 
                         filter(SCS001 == 1 & !is.na(sc_approval)) %>%
                         mutate(sc_approval2 = ifelse(sc_approval==1,"Yes","No")), 
                       aes(rr_scale,sc_approval2)) + 
  geom_violin(fill = "lightgrey",
              draw_quantiles = c(0.25, 0.75),
              linetype = "dashed") +
  geom_violin(fill="transparent",draw_quantiles = 0.5,size=1) + 
  xlab("Racial Resentment Scale") + 
  ylab("Approve of the Supreme Court?") +
  theme_bw(base_size=13) 

pdf(file="Figures/Fig_YouGov_Summary_WhiteRespondents.pdf",8.51,3.85)
cowplot::plot_grid(fig.approval.bar,fig.rr.hist,fig.sc.violin,labels=c("a.","b.","c."),nrow=1)
dev.off()

# Table 14: Correlation Matrix of Supreme Court Approval, Racial Resentment, and Ideology (YouGov Survey, May 2022) [In appendix]
xtable::xtable(cor(kbj %>% filter(SCS001 == 1) %>% select(sc_approval,rr_scale,ideo),
                   use="complete.obs"))

# Regressions: Table 1: Regressions Explaining Supreme Court Approval, YouGov May 2022 [Appendix]
reg.ols = lm(sc_approval ~ factor(kbj_treatment) + 
               IRmarriage_approve + rr_scale  + 
               factor(gender4) + 
               age + pid + ideo + hearings +
               newsint + faminc_new + educ + presvote220,
             data = kbj %>% filter(SCS001 == 1),
             weights = kbj$weight_white[kbj$SCS001 == 1])
reg.logit = glm(sc_approval ~ factor(kbj_treatment) + 
                  IRmarriage_approve + rr_scale  + 
                  factor(gender4) + 
                  age + pid + ideo + hearings +
                  newsint + faminc_new + educ + presvote220,
                data = kbj %>% filter(SCS001 == 1),
                family="binomial",weights = kbj$weight_white[kbj$SCS001 == 1])

texreg(list(reg.ols,reg.logit), stars=0.05,
       custom.coef.map = list("rr_scale"="Racial Resentment",
                              "factor(gender)2"="Woman",
                              "pidInde"="Independent",
                              "pidRep"="Republican",
                              "ideo"="Ideology",
                              "hearings"="Watched Hearings"))

############# Appendix - YouGov - White Respondent Analysis by PID ###############


# Democrats
kbj.dem = kbj %>% filter(SCS001 == 1 & pid == "Dem")
reg.ols.dem = lm(sc_approval ~ factor(kbj_treatment) + 
                   IRmarriage_approve + rr_scale  + 
                   factor(gender4) + 
                   age + hearings +
                   newsint + faminc_new + educ + presvote220,
                 data = kbj.dem,
                 weights = kbj.dem$weight_white)
reg.logit.dem = glm(sc_approval ~ factor(kbj_treatment) + 
                      IRmarriage_approve + rr_scale  + 
                      factor(gender4) + 
                      age + hearings +
                      newsint + faminc_new + educ + presvote220,
                    data = kbj.dem,
                    family="binomial",weights = kbj.dem$weight_white)

# Republicans
kbj.rep = kbj %>% filter(SCS001 == 1 & pid == "Rep")
reg.ols.rep = lm(sc_approval ~ factor(kbj_treatment) + 
                   IRmarriage_approve + rr_scale  + 
                   factor(gender4) + 
                   age + hearings +
                   newsint + faminc_new + educ + presvote220,
                 data = kbj.rep,
                 weights = kbj.rep$weight_white)
reg.logit.rep = glm(sc_approval ~ factor(kbj_treatment) + 
                      IRmarriage_approve + rr_scale  + 
                      factor(gender4) + 
                      age + hearings +
                      newsint + faminc_new + educ + presvote220,
                    data = kbj.rep,
                    family="binomial",weights = kbj.rep$weight_white)

texreg(list(reg.ols,reg.logit,
            reg.ols.dem,reg.logit.dem,
            reg.ols.rep,reg.logit.rep), stars=c(0.05),
       custom.coef.map = list("rr_scale"="Racial Resentment",
                              "factor(gender)2"="Woman",
                              "pidInde"="Independent",
                              "pidRep"="Republican",
                              "ideo"="Ideology",
                              "hearings"="Watched Hearings"))

############# Appendix - YouGov - Appendix Info ###############

# Descriptive Statistics: Table 2: Descriptive Statistics of White Respondents, YouGov May 2022 [Appendix]
yougov.summary = summary.function(variables = kbj %>% 
                                    filter(SCS001 == 1) %>%
                                    mutate(male = ifelse(gender4 == 1, 1, 0),
                                           female = ifelse(gender4 == 2,1,0),
                                           nonbinary = ifelse(gender4 == 3, 1, 0),
                                           dem = ifelse(pid7 %in% 1:3,1,0),
                                           inde = ifelse(pid7==4,1,0),
                                           rep = ifelse(pid7 %in% 5:7,1,0)) %>%
                                    select(sc_approval,rr_scale,
                                           male,female,nonbinary,age,
                                           dem,inde,rep,ideo,
                                           hearings,IRmarriage_approve,
                                           newsint,faminc_new,educ,presvote220),
                                  names = c("Court Approval","RR Scale","Male","Female",
                                            "Non-Binary","Age","Democrat","Indepdent","Republican",
                                            "Ideology (7)","Watched KBJ Hearings","Interracial Marriage Views",
                                            "Interest in Politics","Family Income","Education",
                                            "Presidential Vote ('20)"))

xtable(yougov.summary)

# Regresion Results, by PID: #Regressions: Table 3: Regressions Explaining Supreme Court Approval by Overall and by Party, YouGov May 2022 [Appendix]

texreg(list(reg.ols,reg.logit,
            reg.ols.dem,reg.logit.dem,
            reg.ols.rep,reg.logit.rep), stars=c(0.05),
       custom.coef.map = list("(Intercept)"="Intercept",
                              "rr_scale"="Racial Resentment",
                              "factor(gender)2"="Woman",
                              "factor(gender4)3"="Non-Binary",
                              "age" = "Age",
                              "faminc_new" = "Family Income",
                              "educ" = "Education",
                              "pidInde"="Independent",
                              "pidRep"="Republican",
                              "ideo"="Ideology",
                              "hearings"="Watched Hearings",
                              "newsint"="Interest in Politics",
                              "presvote220"="Voted for President (2020)",
                              "IRMarriage_approve" = "Interracial Marriage Approval",
                              "factor(kbj_treatment)2" = "KBJ Treatment"))


